package com.ly.lypopupwindowdemo.animation;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by liying on 2017/9/27.
 */

public class MyAnimView extends View {

    public static final float RADIUS = 50f;
    private Point currentPoint;
    private Paint mPaint;


    private String color;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
        /**
         * 改变画笔颜色之后立即刷新视图
         */
        mPaint.setColor(Color.parseColor(color));
        invalidate();
    }

    public MyAnimView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.parseColor("#D84C29"));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (currentPoint == null) {
            currentPoint = new Point(RADIUS, RADIUS);
            drawCircle(canvas);
            startAnim();

        } else {
            drawCircle(canvas);
        }

    }

    private void startAnim() {

        Point startPoint = new Point(RADIUS, RADIUS);
        Point endPoint = new Point(getWidth() - RADIUS, getHeight() - RADIUS);

        final ValueAnimator anim = ValueAnimator.ofObject(new PointSinEvaluator(), startPoint, endPoint);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                /**
                 * 每当Point值改变的时候都会回调onAnimationUpdate()方法，
                 * 在这个方法里面对currentPoint重新进行赋值。
                 * 然后调用invalidate()这样会重新调用onDraw方法。
                 * 并且由于currentPoint对象的坐标已经改变了，那么绘制的位置也会改变，于是一个平移的动画效果也就实现了。
                 */
                currentPoint = (Point) animation.getAnimatedValue();
                invalidate();
            }
        });

        anim.setDuration(5000);
        anim.start();

    }

    private void drawCircle(Canvas canvas) {

        float x = currentPoint.getX();
        float y = currentPoint.getY();
        canvas.drawCircle(x, y, RADIUS, mPaint);

    }


}
